package Email.auto.checker;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 * Class responsable for show a popup notification with the number of unreaded
 * emails.
 * 
 * @author Andre Duarte - duarte.andre00gmail.com
 * @author Marcio Almeida - marcio.bastos.almeida@gmail.com
 * 
 */
@SuppressWarnings("serial")
public class Notification extends JFrame {

    /**
     * String that contains the email address.
     */
    private String stringMail;
    /**
     * Variable that contains the number of unread Emails.
     */
    private int numMails;
    /**
     * Variable that contains the size of the computer screen.
     */
    private Dimension screenDim;

    /**
     * The container for the window.
     */
    private Container cp;
    /**
     * The button that will be used to open the web browser.
     */
    private JButton buttonOpenBrowser;
    /**
     * The button used to close the notification.
     */
    private JButton buttonClose;
    /**
     * Component used to display a string with the number os new unread emails.
     */
    private JLabel labelNewMessage;
    /**
     * Component used to display a string with the emails address used.
     */
    private JLabel labelLogged;
    /**
     * Component used to display the number of unread emails.
     */
    private JLabel labelNumberNewEmails;
    /**
     * Constaints the close and open in browser buttons.
     */
    private JPanel panelNorth;
    /**
     * Constains the label "labelNewMessage".
     */
    private JPanel panelCenter;
    /**
     * Layout used to show a message with the number of unread emails.
     */
    private GridBagConstraints c;
    /**
     * Reference to the class notification
     * */
    private Notification notification;

	/**
	 * The only constructor used to create the notification.
	 * 
	 * @param mail 
	 *            - the email address used
	 * @param nMails
	 *            - the number of new unread email
	 */
	public Notification(final String mail, final int nMails) {
		
        this.setIconImage(createImage("images/email_autoCheckerIcon.png",
				"Email AutoChecker"));

		if (mail == null || nMails < 0 || !verifyFields(mail)) {
			System.out.println("nMails: " + nMails + " mail: " + mail);
			throw new IllegalArgumentException();
		}
		
		
		notification = this;
		
		stringMail = mail;
		numMails = nMails;

		cp = getContentPane();
		cp.setLayout(new BorderLayout());
		cp.setBackground(new Color(24, 24, 24));

		makeObject();
		arrangeComponents();
		addListener();

		this.setSize(new Dimension(ConstNotification.WIDTH_WINDOW,
				ConstNotification.HEIGHT_WINDOW));

		screenDim = Toolkit.getDefaultToolkit().getScreenSize();
		this.setLocation(
				(int) (screenDim.getWidth() - ConstNotification.WIDTH_WINDOW) - 10,
				(int) (screenDim.getHeight() - ConstNotification.HEIGHT_WINDOW - ConstNotification.BARRA_TAREFAS_TAM));

		this.setResizable(false);
		this.setUndecorated(true);
		this.setVisible(true);
		this.setAlwaysOnTop(true);
		this.toFront();
		
		Thread t = new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					Thread.sleep(5000);
					notification.dispose();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				
			}
		});
		t.start();
	}

	/**
	 * Method to add the listeners to the buttons.
	 */
	private void addListener() {
		if (buttonClose == null || buttonOpenBrowser == null) {
			return;
		}
		buttonClose.addActionListener(new ClickButtonClose(this));
		buttonOpenBrowser.addActionListener(new ClickButtonOpenBrowser(this));
	}

	/**
	 * Method used to arrange the notification components.
	 */
	private void arrangeComponents() {
		panelNorth.add(buttonOpenBrowser);
		panelNorth.add(buttonClose);
		panelCenter.add(labelNewMessage, c);

		c.gridy = 2;
		panelCenter.add(labelLogged, c);

		cp.add(panelNorth, BorderLayout.NORTH);
		cp.add(labelNumberNewEmails, BorderLayout.WEST);
		cp.add(panelCenter, BorderLayout.CENTER);
	}

	/**
	 * Method used to create new instances of the components.
	 */
	private void makeObject() {
		panelNorth = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		Color colorNorth = new Color(24, 24, 24);
		panelNorth.setBackground(colorNorth);

		c = new GridBagConstraints();
		panelCenter = new JPanel(new GridBagLayout());
		Color colorCenter = new Color(24, 24, 24);
		panelCenter.setBackground(colorCenter);
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 0;
		c.gridy = 1;

		buttonOpenBrowser = new JButton("Open in Browser");
		buttonOpenBrowser.setBackground(new Color(82, 94, 97));
		buttonOpenBrowser.setForeground(Color.WHITE);
		buttonOpenBrowser.setBorderPainted(false);
		buttonOpenBrowser.setFocusPainted(false);
		buttonClose = new JButton("X");
		buttonClose.setBackground(Color.RED);
		buttonClose.setForeground(Color.WHITE);
		buttonClose.setBorderPainted(false);
		buttonClose.setFocusPainted(false);

		Font font = new Font("Calibri", Font.BOLD, 20);
		labelLogged = new JLabel("Logged in as: " + stringMail);
		labelLogged.setFont(new Font("Calibri", Font.ITALIC, 12));
		labelLogged.setForeground(Color.LIGHT_GRAY);
		labelNewMessage = new JLabel("You have " + numMails + " new messages");
		labelNewMessage.setFont(font);
		labelNewMessage.setForeground(new Color(255, 255, 255));
		labelNumberNewEmails = new JLabel("" + numMails);
		labelNumberNewEmails.setFont(new Font("Calibri", Font.BOLD, 50));
		labelNumberNewEmails.setBackground(new Color(24, 24, 24));
		labelNumberNewEmails.setForeground(new Color(255, 255, 255));
	}

	/**
	 * Get the email address used.
	 * 
	 * @return email address used in the application.
	 */
	public final String getStringMail() {
		return stringMail;
	}

	/**
	 * Set the email address used.
	 * 
	 * @param stringM
	 *            - Email address used in the application
	 */
	public final void setStringMail(final String stringM) {
		if (stringM == null) {
			this.stringMail = null;
			return;
		}
		if (!verifyFields(stringM)) {
			this.stringMail = null;
			return;
		}
		this.stringMail = stringM;
	}

	/**
	 * Verify if email address is @gmail.com or @hotmail.com or @isec.pt
	 * 
	 * @param mail
	 *            - Email address used in the application
	 * @return true - if address is @gmail.com or @hotmail.com or @isec.pt</br>
	 *         false - otherwise
	 */
	public final boolean verifyFields(final String mail) {
		String regExpr;
		String user;
		String domain;
		String[] part;

		regExpr = "[a-zA-Z_0-9]";
		if (mail.contains("@")) {
			part = mail.split("@");
			user = part[0];
			domain = part[1];
			user.matches(regExpr);

			if (!(domain.equals("isec.pt")) && !(domain.equals("gmail.com"))
					&& !(domain.equals("hotmail.com"))) {
				return false;
			}

			return true;
		}
		return false;
	}

	protected static Image createImage(String path, String description) {
		URL imageURL = Tray.class.getResource(path);

		if (imageURL == null) {
			System.err.println("Resource not found: " + path);
			return null;
		} else {
			return (new ImageIcon(imageURL, description)).getImage();
		}
	}
	
}
